package com.dynamic.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;

/**
 * TODO
 *
 * @author 库琦
 * @version 1.0
 * @date 2022/6/14 14:41
 */
public class DynamicRedisTemplateFactory<K,V> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicRedisTemplateFactory.class);
    private final RedisProperties properties;
    private static final String REDIS_CLIENT_LETTUCE = "lettuce";
    private static final String REDIS_CLIENT_JEDIS = "jedis";

    public DynamicRedisTemplateFactory(RedisProperties properties) {
        this.properties = properties;

    }
    public RedisTemplate<K,V> createRedisTemplate(int database){
        RedisConnectionFactory redisConnectionFactory = null;
        switch (getRedisClientType()){
            case REDIS_CLIENT_LETTUCE:
                LettuceConnectionConfigure lettuceConnectionConfigure = new LettuceConnectionConfigure(
                        properties, database);
                redisConnectionFactory = lettuceConnectionConfigure.redisConnectionFactory();
                break;
            case REDIS_CLIENT_JEDIS:
                JedisConnectionConfigure jedisConnectionConfigure = new JedisConnectionConfigure(properties, database);
                redisConnectionFactory = jedisConnectionConfigure.redisConnectionFactory();
            default:
                LOGGER.error("unknow redis client type.");
        }
        Assert.notNull(redisConnectionFactory, "redisConnectionFactory is null.");
        return createRedisTemplate(redisConnectionFactory);
    }

    /**
     * 通过Redis连接工厂来创建一个redisTemplate用于操作Redis db
     */
    private RedisTemplate<K, V> createRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<K, V> template = new RedisTemplate<K, V>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 获取Redis客户端的类型，提供jedis和lettuce两种。
     * @return
     */
    private static String getRedisClientType(){
        RedisConnectionFactory redisConnectionFactory = null;
        try {
            // 如果能加载lettuce，则优先使用lettuce
            Class.forName("io.lettuce.core.RedisClient");
            return REDIS_CLIENT_LETTUCE;
        } catch (ClassNotFoundException e) {
            LOGGER.debug("Not Lettuce redis client");
        }
        try {
            // 如果能加载Jedis，则使用Jedis
            Class.forName("redis.clients.jedis.Jedis");
            return REDIS_CLIENT_JEDIS;
        } catch (ClassNotFoundException e) {
            LOGGER.debug("Not Jedis redis client");
        }

        throw new RuntimeException("redis client not found.");
    }


}
